import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { InjectionKey } from 'vue'
import { State } from '@vue/runtime-core'


import getters from './getters'

function loadModules() {
  const requireModules = import.meta.globEager("./modules/([a-zA-Z_]+)\.ts")
  
  const modules: any = {}
  for (let i in requireModules) {
    // 将模块路径切割出模块名
    const moduleName = i
      .split("/")
    [i.split("/").length - 1].replace(".ts", "")
    // 将模块放入modules
    modules[moduleName] = requireModules[i]?.default
  }

  return { requireModules, modules }
}

const { modules } = loadModules()
// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol()
//初始化 store 
const store = createStore({
  strict: import.meta.env.NODE_ENV !== 'production',  //严格模式不在生产环境
  modules,
  getters
})

// 定义自己的 `useStore` 组合式函数,就可以直接调用
// const store = useStore()
//  store.state.count // 类型为 number

export function useStore() {
  return baseUseStore(key)
}


export default store